package example.book.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class MainFrame extends JFrame {
    private User currentUser;
    private JList<Book> bookList;
    private DefaultListModel<Book> listModel;

    public MainFrame(User user) {
        this.currentUser = user;
        setTitle("图书管理系统 - 欢迎 " + user.getUsername());
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        listModel = new DefaultListModel<>();
        updateBookList();

        bookList = new JList<>(listModel);
        bookList.setCellRenderer(new BookListRenderer());
        JScrollPane scrollPane = new JScrollPane(bookList);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        if ("admin".equals(user.getRole())) {
            JButton addButton = new JButton("添加图书");
            addButton.addActionListener(e -> addBook());
            buttonPanel.add(addButton);
        }

        JButton borrowButton = new JButton("借书");
        borrowButton.addActionListener(e -> borrowBook());
        buttonPanel.add(borrowButton);

        JButton returnButton = new JButton("还书");
        returnButton.addActionListener(e -> returnBook());
        buttonPanel.add(returnButton);

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> updateBookList());
        buttonPanel.add(refreshButton);

        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        setVisible(true);
    }

    private void updateBookList() {
        listModel.clear();
        List<Book> books = Database.getAllBooks();
        for (Book book : books) {
            listModel.addElement(book);
        }
    }

    private void addBook() {
        JTextField idField = new JTextField();
        JTextField titleField = new JTextField();
        JTextField authorField = new JTextField();

        JPanel panel = new JPanel(new GridLayout(3, 2));
        panel.add(new JLabel("图书编号:"));
        panel.add(idField);
        panel.add(new JLabel("书名:"));
        panel.add(titleField);
        panel.add(new JLabel("作者:"));
        panel.add(authorField);

        int result = JOptionPane.showConfirmDialog(this, panel,
                "添加新书", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String id = idField.getText();
            String title = titleField.getText();
            String author = authorField.getText();

            if (!id.isEmpty() && !title.isEmpty() && !author.isEmpty()) {
                Database.addBook(new Book(id, title, author));
                updateBookList();
            } else {
                JOptionPane.showMessageDialog(this,
                        "所有字段都必须填写!", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void borrowBook() {
        Book selectedBook = bookList.getSelectedValue();
        if (selectedBook == null) {
            JOptionPane.showMessageDialog(this,
                    "请先选择一本书!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (!selectedBook.isAvailable()) {
            JOptionPane.showMessageDialog(this,
                    "该书已被借出!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (Database.borrowBook(selectedBook.getId())) {
            JOptionPane.showMessageDialog(this,
                    "借书成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            updateBookList();
        } else {
            JOptionPane.showMessageDialog(this,
                    "借书失败!", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void returnBook() {
        Book selectedBook = bookList.getSelectedValue();
        if (selectedBook == null) {
            JOptionPane.showMessageDialog(this,
                    "请先选择一本书!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (selectedBook.isAvailable()) {
            JOptionPane.showMessageDialog(this,
                    "该书未被借出!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (Database.returnBook(selectedBook.getId())) {
            JOptionPane.showMessageDialog(this,
                    "还书成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            updateBookList();
        } else {
            JOptionPane.showMessageDialog(this,
                    "还书失败!", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 自定义图书列表渲染器
    private class BookListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value,
                                                      int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            Book book = (Book) value;
            String status = book.isAvailable() ? "可借" : "已借出";
            setText(String.format("%s - %s (作者: %s) [%s]",
                    book.getId(), book.getTitle(), book.getAuthor(), status));

            if (!book.isAvailable()) {
                setForeground(Color.RED);
            } else {
                setForeground(Color.BLACK);
            }

            return this;
        }
    }
}
